package server

import (
	V1 "open/api/open/service/v1"
	"open/internal/conf"
	"open/internal/service"
	"open/pkg/log"
	"open/pkg/middleware/validate"

	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/propagation"

	"open/pkg/middleware/logging"
	"open/pkg/middleware/recovery"
)

// NewGRPCServer new a gRPC server.
func NewGRPCServer(c *conf.Server, open *service.Service) *grpc.Server {
	var mm []middleware.Middleware
	if tp := otel.GetTracerProvider(); tp != nil {
		mm = append(mm, tracing.Server(
			tracing.WithTracerProvider(tp),
			tracing.WithPropagators(
				propagation.NewCompositeTextMapPropagator(propagation.Baggage{}, propagation.TraceContext{}),
			)))
	}
	mm = append(mm, []middleware.Middleware{
		logging.Server(),
		recovery.Recovery(),
		validate.Validator(),
	}...)
	var opts = []grpc.ServerOption{
		grpc.Middleware(
			middleware.Chain(
				mm...,
			),
		),
	}
	if c.Grpc.Network != "" {
		opts = append(opts, grpc.Network(c.Grpc.Network))
	}
	if c.Grpc.Addr != "" {
		opts = append(opts, grpc.Address(c.Grpc.Addr))
	}
	if c.Grpc.Timeout != nil {
		opts = append(opts, grpc.Timeout(c.Grpc.Timeout.AsDuration()))
	}
	opts = append(opts, grpc.Logger(log.NewZapLogger()))
	srv := grpc.NewServer(opts...)
	V1.RegisterOpenServiceServer(srv, open)
	return srv
}
